package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Transactional
    public void add(DishDto dishDto) {
        //1. 添加菜品
        this.save(dishDto);
        //拿到添加后的菜品id
        Long dishId = dishDto.getId();

        //2. 添加口味
        //2.1 拿到口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        //2.2 将菜品id绑定到口味上
        List<DishFlavor> list = flavors.stream().map(flavor -> {
            flavor.setDishId(dishId);
            return flavor;
        }).collect(Collectors.toList());

        //2.3 添加口味 -- 批量添加
        dishFlavorService.saveBatch(list);
    }

    @Override
    public void updateWithFlavors(DishDto dishDto) {
        //1. 修改菜品
        this.updateById(dishDto);

        //2. 维护菜品对应的口味信息
        //2.1 将数据库中记录的老的口味数据删除
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(wrapper);

        //2.2 将新的口味数据添加进数据库
        List<DishFlavor> flavors = dishDto.getFlavors();
        //2.3 将菜品id绑定到口味上
        List<DishFlavor> list = flavors.stream().map(flavor -> {
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());

        //2.3 添加口味 -- 批量添加
        dishFlavorService.saveBatch(list);
    }
}
